package com.link.play.fit.ai.ui.weightcontrol.ac

import android.os.Build
import android.os.Bundle
import androidx.activity.addCallback
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.AcWeighControlReadyBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ui.main.fragment.control.ControlResutAc
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class WeighControlReadyAc : BaseActivity<AcWeighControlReadyBinding>(AcWeighControlReadyBinding::inflate) {

    val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[WeighControlViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.lastUserGuide = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra("data", UserGuide::class.java) ?: UserGuide()
        } else {
            @Suppress("DEPRECATION")
            (intent.getSerializableExtra("data") as UserGuide?) ?: UserGuide()
        }

        lifecycleScope.launch(Dispatchers.IO) {

            delay(Random.nextLong(1000, 1500))
            launch(Dispatchers.Main) {
                binding.tvLoad.text = getString(R.string.applying_bmr_formula)
            }

            delay(Random.nextLong(1000, 1500))
            launch(Dispatchers.Main) {
                binding.tvLoad.text = getString(R.string.customizing_health_plan)
            }

            delay(Random.nextLong(1000, 1500))
            launch(Dispatchers.Main) {
                binding.tvLoad.text = getString(R.string.finalizing_results)
//                binding.tvNext.isEnabled = true
                delay(500)
                next()
            }

        }



        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }

        binding.tvNext.setOnClickListener {
            next()
        }
    }

    fun next() {
        "viewModel.lastUserGuide  ${viewModel.lastUserGuide}".d()
        goToAc(ControlResutAc::class.java) {
            putExtra("user", viewModel.lastUserGuide)
        }
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left)
        finish()
    }

}